/*
 *  @author zhangqiang
 *  @data 2017/07/26
 *   添加地址
 * */

import React, { Component } from 'react';
import {Toast,Picker, List} from 'antd-mobile';
import { createForm } from 'rc-form';
import { Title } from '../../components/common'
import {
	address,
	setAddAddress
} from '../../actions/addAddressActions';

import {
	allAddressData
} from '../../components/common/addressData'

import NotExpression from '../../utils/expression'

import style from './index.scss'
import {connect} from 'react-redux';
import {InputItem} from '../../components/home'
import common from '../../utils/common'
import 'style/addAddress.scss';

class addAddress extends Component {
    constructor(props) {
        super(props);
        this.state = {
	        name: '', //姓名 自由类型
	        nameImg: false,
	        nameWidth: '.3rem', // 姓名的默认宽度
	        nameNoBlur: true, //点击删除按钮不执行失去焦点验证

	        phone: '', //姓名 自由类型
	        phoneImg: false,
	        phoneWidth: '.3rem', // 姓名的默认宽度
	        phoneNoBlur: true, //点击删除按钮不执行失去焦点验证

	        details: '', //详细信息
	        addressData: '', //省市区地址数据
        }
    }

    componentWillMount() {

    }

    componentDidMount() {
	    common.setViewTitle('添加地址');


			// common.backShowConfirm(()=>{
	    	//监听返回事件
			// })

    }

    componentWillUnmount() {

    }

    getAllAddressData(){
	    let getData={
		    provinceId: 440000,
		    bizType: 0
	    };
	    address(getData,(res)=>{
		    this.setState({
			    addressData: res
		    })
	    })
    }

		/*
		 *   省市区
		 * */
		getRegion(e){
			document.querySelector('.am-list-extra').style.color='#1a1a1a';
		}

	toUrl(url) {
		this.context.router.push(url);
	}

	subMit(){
			this.props.form.validateFields((error, value) => {
				let telNum = this.state.phone.replace(/\s+/g, ""),
					reg = /^0?1[3|4|5|7丨8][0-9]\d{8}$/,
					// reg_name = /^[a-zA-Z\u4e00-\u9fa5\s]{1,20}$/,
					 reg_name = /^[\u4e00-\u9fa5]{2,12}$/,
					reg_details = /^[\u4e00-\u9fa5]{5,100}$/;
				// if (!this.state.name && !this.state.phone && !this.state.district && !value.focus) {
				// 	Toast.info('请填写资料', 1);
				// 	return false;
				// } else {

					if (this.state.name == '' || !this.state.name || this.state.name.replace(/(^\s*)|(\s*$)/g, "") == "") {
						Toast.info('请输入正确的收件人姓名', 1);
						return false;
					} else if (!reg_name.test(this.state.name)) {
						Toast.info('姓名格式错误', 1)
						return false;
					} else if (NotExpression.isEmojiCharacter(this.state.name.toString())) {
						Toast.info('姓名不能包含表情', 1);
						return false;
					} else if (this.state.phone == '' || !this.state.phone) {
						Toast.info('请输入正确的联系电话', 1);
						return false;
					} else if (!reg.test(telNum)) {
						Toast.info('手机格式错误', 1)
						return false;
					} else if (!value.district) {
						Toast.info('提示请选择省市区（县）', 1);
						return false;
					} else if (this.state.details == '' || !this.state.details|| this.state.details.replace(/(^\s*)|(\s*$)/g, "") == "") {
						Toast.info(' 请输入详细地址', 1);
						return false;
					} else if (this.state.details.toString().length < 5) {
						Toast.info('详细地址长度应不少于5位', 1);
						return false;
					}
					// else if(!reg_details.test(this.state.details)){
					// 	Toast.info('详细地址格式错误', 1);
					// 	return false;
					// }

				//}
				let countyName = value.district[2] ? value.district[2].split(',')[0] : '';//所在区
				let fullAddr = value.district[0].split(',')[0]+value.district[1].split(',')[0]+value.district[2].split(',')[0]+this.state.details;
				let postData = {
					contactName: this.state.name,
					cellNum: this.state.phone,
					street: this.state.details,
					provinceId: value.district[0] ? value.district[0].split(',')[1] : null, //省份code
					provinceName: value.district[0] ? value.district[0].split(',')[0] : tnull, //省份

					cityId: value.district[1] ? value.district[1].split(',')[1] : null,//城市code
					cityName: value.district[1] ? value.district[1].split(',')[0] : null,//城市

					countyId: value.district[2] ? value.district[2].split(',')[1] : '',//所在区code
					countyName: countyName.replace(null,''),

					fullAddr: fullAddr.replace(null,'')
				};
				setAddAddress(postData,()=>{
					Toast.info('添加成功',1)
					setTimeout(()=>{this.toUrl('addressList')},250)
				})
			});
		}

    render() {
	    const { getFieldProps } = this.props.form;
			let that = this;
	    return (
        <div className={style.addAddress}>
	        <div style={{height: '.24rem'}}></div>
	        <div>
		        <Title text='邮政速递人员将按此地址上门取件和送件，请准确、完整的填写' isLine={true}/>
		        <InputItem type="text" index='2' itemText="姓名" maxLength="12" placeHolder="收件人姓名" id="name"
		                   value={this.state.name} showUnderLine={true} showTagText={false} creditCodeImg={this.state.nameImg} creditWidth = {this.state.nameWidth}
		                   onClick={()=>{
			                   this.setState({
				                   name: '',
				                   nameImg: 'hideDelete',
				                   nameNoBlur: false
			                   })

			                   document.querySelector('#name').focus();
		                   }}
		                   onBlur={(event)=>{
			                   let res = event.target.value;
			                   this.setState({nameNoBlur: true});
			                   setTimeout(()=>{
				                   if(!this.state.nameNoBlur) return;  //点击删除按钮不执行验证
				                   let value = res,
					                   nameRule1= /^[\u4e00-\u9fa5]{2,12}$/;

				                   if(value == ''){
					                   this.setState({
						                   nameImg: '',
					                   });
				                   }else if(nameRule1.test(value)){
					                   this.setState({
						                   nameImg: 'correct',
						                   nameWidth: '.4rem'
					                   });
				                   }else {
					                   this.setState({
						                   nameWidth: '.4rem',
						                   nameImg: 'error'
					                   })
				                   }
			                   },0)
		                   }}

		                   onFocus={(e)=>{
			                   let value = e.target.value;
			                   if(value.length!=0&&this.state.name==value){
				                   this.setState({
					                   nameImg: 'showDelete',
				                   });
			                   }
		                   }}

		                   onChange={(e) => {
			                   let value = e.target.value;
			                   if(value.length>0&&value!=' '){
				                   this.setState({
					                   nameImg: 'showDelete',
					                   name: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
				                   });
			                   }else {
				                   this.setState({
					                   nameImg: 'hideDelete',
					                   name: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
				                   });
			                   }
		                   }}/>

		        <InputItem type="text" index='2' itemText="联系电话" maxLength="11" placeHolder="联系电话" id="phone"
		                   value={this.state.phone} showUnderLine={false} showTagText={false} creditCodeImg={this.state.phoneImg} creditWidth = {this.state.phoneWidth}
		                   onClick={()=>{
			                   this.setState({
				                   phone: '',
				                   phoneImg: 'hideDelete',
				                   phoneNoBlur: false
			                   })
			                   document.querySelector('#phone').focus();
		                   }}
		                   onBlur={(event)=>{
			                   let res = event.target.value;
			                   this.setState({phoneNoBlur: true});
			                   setTimeout(()=>{
				                   if(!this.state.phoneNoBlur) return;  //点击删除按钮不执行验证
				                   let value = res,
					                   phoneRule = /^0?1[3|4|5|7丨8][0-9]\d{8}$/;

				                   if(value == ''){
					                   this.setState({
						                   phoneImg: '',
					                   });
				                   }else if(phoneRule.test(value)){
					                   this.setState({
						                   phoneImg: 'correct',
						                   phoneWidth: '.4rem'
					                   });
				                   }else {
					                   this.setState({
						                   phoneWidth: '.4rem',
						                   phoneImg: 'error'
					                   })
				                   }
			                   },0)
		                   }}

		                   onFocus={(e)=>{
			                   let value = e.target.value;
			                   if(value.length!=0&&value==this.state.phone){
				                   this.setState({
					                   phoneImg: 'showDelete',
				                   });
			                   }
		                   }}

		                   onChange={(e) => {
			                   let value = e.target.value;
			                   if(value.length>0&&value!=' '){
				                   this.setState({
					                   phoneImg: 'showDelete',
					                   phone: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
				                   });
			                   }else {
				                   this.setState({
					                   phoneImg: 'hideDelete',
					                   phone: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
				                   });
			                   }
		                   }}/>
		        <div style={{height: '.24rem'}}></div>

		        <Picker extra="省、市、区（县）" data={allAddressData.value}//addressDataAll.data.valuethis.state.addressData
		                format={(values) => { { return values.join(''); } }}
		                title="选择地区" {...getFieldProps('district', {
			        onChange(e) {
				        that.getRegion(e)
			        },
		        }) }
		        >
			        <List.Item arrow="horizontal"></List.Item>
		        </Picker>
		        <div className="border_bottom_1" style={{position: 'relative',paddingLeft: '.3rem'}}></div>
		        <InputItem type="text" index='2' itemText="详细地址" maxLength="50" placeHolder="详细地址" id="details"
		                   value={this.state.details} showUnderLine={true} showTagText={false} creditCodeImg={this.state.detailsImg} creditWidth = {this.state.detailsWidth}
		                   onClick={()=>{
			                   this.setState({
				                   details: '',
				                   detailsImg: 'hideDelete',
				                   detailsNoBlur: false
			                   })
			                   document.querySelector('#details').focus();
		                   }}
		                   onBlur={(event)=>{
			                   let res = event.target.value;
			                   this.setState({detailsNoBlur: true});
			                   setTimeout(()=>{
				                   if(!this.state.detailsNoBlur) return;  //点击删除按钮不执行验证
				                   let value = res;
					                  // {/*detailsRule1= /^[\u4e00-\u9fa5]{5,100}$/;*/}

				                   if(value == ''){
					                   this.setState({
						                   detailsImg: '',
					                   });
				                   }
				                  // else if(detailsRule1.test(value)){
					                  // this.setState({
						                  // detailsImg: 'correct',
						                  // detailsWidth: '.4rem'
					                  // });
				                //   }
				                   else if(value.length>=5){
					                   this.setState({
						                   detailsWidth: '.4rem',
						                   detailsImg: 'correct'
					                   })
				                   }else {
					                   this.setState({
						                   detailsWidth: '.4rem',
						                   detailsImg: 'error'
					                   })
				                   }

			                   },0)
		                   }}

		                   onFocus={(e)=>{
			                   let value = e.target.value;
			                   if(value.length!=0&&value==this.state.details){
				                   this.setState({
					                   detailsImg: 'showDelete',
				                   });
			                   }
		                   }}

		                   onChange={(e) => {
			                   let value = e.target.value;
			                   if(value.length>0&&value!=' '){
				                   this.setState({
					                   detailsImg: 'showDelete',
					                   details: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
				                   });
			                   }else {
				                   this.setState({
					                   detailsImg: 'hideDelete',
					                   details: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
				                   });
			                   }
		                   }}/>
	        </div>

	        <div className={style.footBtn}>
						<button type="button" onClick={()=>{this.subMit()}}>保存</button>
		        <div className={style.cancel}>取消</div>
	        </div>
        </div>
      );
    }
}


addAddress.contextTypes = {
	router: React.PropTypes.object.isRequired
}

export default createForm()(addAddress);
